import monitor from "../utils/monitor"

chrome.runtime.onInstalled.addListener(async (opt) => {
  // Check if reason is install or update. Eg: opt.reason === 'install' // If extension is installed.
  // opt.reason === 'update' // If extension is updated.
  if (opt.reason === 'install') {
    await chrome.storage.local.clear()

    chrome.tabs.create({
      active: true,
      // Open the setup page and append `?type=install` to the URL so frontend
      // can know if we need to show the install page or update page.
      url: chrome.runtime.getURL('./src/setup/index.html?type=install'),
    })
  }

  if (opt.reason === 'update') {
    chrome.tabs.create({
      active: true,
      url: chrome.runtime.getURL('./src/setup/index.html?type=update'),
    })
  }
})

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  console.log('back ----- onMessage', message)
  if (message.event == 'addMonitor') {
    return monitor.addMonitor(message.data)
  }  
  if (message.event == 'startMonitor') {
    return monitor.startMonitor(message.data)
  }
  if (message.event == 'deleteMonitor') {
    return monitor.deleteMonitor(message.data)
  }  
  if (message.event == 'clearMonitor') {
    return monitor.clearMonitor()
  }
  if (message.event == 'pauseMonitor') {
    return monitor.pauseMonitor(message.data)
  }
  if (message.event == 'clearEvent') {
    return monitor.clearEvent()
  }
  return true
})


chrome.notifications.onButtonClicked.addListener(function(notifId, buttonIndex) {
  if (notifId === "myNotificationID") {
      if (buttonIndex === 0) {
          // 处理按钮 1 的点击事件
          alert("Button 1 clicked.");
          console.log("Button 1 clicked.");
      } else if (buttonIndex === 1) {
          // 处理按钮 2 的点击事件
          console.log("Button 2 clicked.");
      }
  }
});

// 想contentscript发消息

// chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
//   if (tabs && tabs.length > 0) {
//     const activeTab = tabs[0];
//     console.log('当前活动标签页的是：', activeTab);
//     try {
//         chrome.tabs.sendMessage(activeTab.id, {'evt':'mediaUrl','data':mediaUrl }, function (res) {
//             console.log(res);
//         });
//     } catch (error) {
//         console.error(error.message);
//     }
//   }
// });
console.log('hello world from background')

self.onerror = function (message, source, lineno, colno, error) {
  console.info(
    `Error: ${message}\nSource: ${source}\nLine: ${lineno}\nColumn: ${colno}\nError object: ${error}`
  )
}

export {}
